#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <cstring>

using namespace std;

#define N 2
#define NUM 1024

void Write(int wfd)
{
    string s = "child message";
    pid_t pid = getpid();
    int num = 0;

    char buffer[NUM];
    while(1)
    {
        buffer[0] = 0;
        snprintf(buffer,sizeof(buffer),"%s,%d,%d",s.c_str(),pid,num++);
        cout<<"child buffer = "<<buffer<<endl;
        write(wfd,buffer,strlen(buffer));
        // sleep(5);
    }
}
void Read(int rfd)
{
    char buffer[NUM];
    while(1)
    {
        sleep(1);
        buffer[0]=0;
        ssize_t n = read(rfd,buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;
        }
        cout<<"father buffer :"<<getpid()<<"-"<<buffer<<endl;
    }
}

int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if(n<0) return 1;

    pid_t id = fork();
    if(id == 0)
    {
        //子进程
        //子进程作为写端要关闭读端接口
        close(pipefd[0]);
        //子进程的写操作
        Write(pipefd[1]);
        close(pipefd[1]);
    }
    else if(id > 0)
    {
        //父进程
        //父进程进行读操作就需要关闭写端接口
        close(pipefd[1]);
        //父进程的读数据操作
        Read(pipefd[0]);
        //父进程要等待子进程，以回收子进程，防止僵尸进程消耗资源
        pid_t rid = waitpid(id,nullptr,0);
        if(rid<0)
        {
            cout<<"wait fail"<<endl;
            return 3;
        }
        close(pipefd[0]);
    }
    else
    {
        //创建失败
        return 2;
    }
    // cout<<"pipefd[0] = "<<pipefd[0]<<" pipefd[1] = "<<pipefd[1]<<endl;

    return 0;
}
